package android.slc.sys.ui;

import android.app.Application;
import android.slc.appbase.api.slc.callback.SlcObserver;
import android.slc.appbase.ui.utils.LoadingUtils;
import android.slc.appbase.utils.AutoServiceUtils;
import android.slc.appbase.vm.AppBaseViewModel;
import android.slc.appbase.vm.GlobalDataVm;
import android.slc.extras.main_biz.repository.local.MainBizLocalService;
import android.slc.extras.system.domain.StartupPermissionsVmBox;
import android.slc.extras.system.domain.StartupUiTaskVmBox;
import android.slc.extras.user.entity.UserInfo;
import android.slc.extras.user.repository.local.UserLocalService;
import android.slc.extras.user.repository.local.UserSp;
import android.slc.extras.user.repository.remote.UserServiceRepository;
import android.slc.or.SlcCallbackConfig;
import android.slc.sys.R;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableBoolean;
import androidx.lifecycle.Observer;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;

/**
 * @author slc
 * @date 2020-07-10 11:31
 */
public class WelcomeVm extends AppBaseViewModel {
    public final ObservableBoolean isLoading = new ObservableBoolean(false);
    public final StartupUiTaskVmBox startupUiTaskVmBox = new StartupUiTaskVmBox();
    public final StartupPermissionsVmBox startupPermissionsVmBox = new StartupPermissionsVmBox();
    public WelcomeVm(@NonNull Application application) {
        super(application);
    }

    public void init() {
        registerVmBox(startupUiTaskVmBox);
        registerVmBox(startupPermissionsVmBox);
        startupPermissionsVmBox.allPermissionsGrantedVd().observeForever(new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                isLoading.set(true);
                tryLogin();
            }
        });
        startupUiTaskVmBox.getUiTaskEndVd().observeForever(new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                startupPermissionsVmBox.checkPermission();
            }
        });
        startupUiTaskVmBox.start();
    }

    private void tryLogin() {
        if (UserSp.isAutoLogin() && !StringUtils.isEmpty(UserSp.getCurrentUser()) && !StringUtils.isEmpty(UserSp.getCurrentUserPassword())) {
            UserServiceRepository.login(UserSp.getCurrentUser(), UserSp.getCurrentUserPassword())
                    .to(bindToLifecycle())
                    .subscribe(new SlcObserver<UserInfo>(SlcCallbackConfig.newBuilder()
                            .setDialogMsg(R.string.app_label_logging_in)
                            .setToastRes(R.string.app_toast_login_login_failed).build()) {
                        @Override
                        public void onSucceed(UserInfo data) {
                            ToastUtils.showShort(R.string.app_toast_login_login_successful);
                            UserSp.saveCurrentUserId(data.getId());
                            GlobalDataVm.getInstance().userVmBox.userOf.set(data);
                            LoadingUtils.dismissLoadingDialog();
                            //登录主页
                            startActivity(AutoServiceUtils.load(MainBizLocalService.class).getMainClass());
                            finish();
                        }

                        @Override
                        public void onFailed(int errorCode, String errorMessage) {
                            UserSp.setAutoLogin(false);
                            startActivity(AutoServiceUtils.load(UserLocalService.class).getLoginClass());
                            finish();
                        }
                    });
        } else {
            startActivity(AutoServiceUtils.load(MainBizLocalService.class).getMainClass());
            //startActivity(AutoServiceUtils.load(UserLocalService.class).getLoginClass());
            finish();
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        ThreadUtils.getMainHandler().removeCallbacksAndMessages(null);
    }
}
